/*****  Component, by Ben Bi <prince.bi@gmail.com>  created at: 12/23/2009 4:10:45 PM  *****/

/********   Notes:  *******
 *  Two tags need to be replaced with the module name, they are:
 *  weaveQcForm
 *  WeaveQcForm
 *  weave_qc_form
 *  set panel.id
 */



/***** variables declartion section, begin *****/
var weaveQcFormInputMode = wacFormInputMode.add;
var weaveQcFormObj = {};
var weaveQcFormAuditAction = {};

/***** variables declartion section, end *****/

/***** init section, begin *****/
$(document).ready(
    function() {
        weaveQcFormAuditAction = new WeaveQcFormAuditAction();

        initWeaveQcFormFormDialog();

        initWeaveQcFormForm();

        bindWeaveQcFormEvents();
    }
);

function bindWeaveQcFormEvents()
{
    $("#weaveQcFormFormDialog").bind('dialogopen', function(event, ui)
    {
        initWeaveQcFormFormData();
//        wacDebugLog("calling " + moduleName + ":" + wacModelObj.weaveQcForm.name);//
    });

    $("#weaveQcFormFormDialog").bind('dialogclose', function(event, ui)
    {
        $.validationEngine.closePrompt(".formError", true);
    });

    $("#weaveQcForm_btnSubmit").bind('click', function (e)
    {
        submitWeaveQcFormForm();
    });

    $("#weaveQcForm_btnClose").bind('click', function (e)
    {
        $("#weaveQcFormFormDialog").dialog('close');
    });

    // fix dialog div didnt remove bug, remove it by this way
    $('#appStorehouseRightPane').bind('tabsremove', function(event, ui) {
        if(ui.panel.id == "t14002")
        {
            $("div[aria-labelledby='ui-dialog-title-weaveQcFormFormDialog']").remove();
            $("#weaveQcFormFormDialog").remove();
        }
    });
}


function initWeaveQcFormFormDialog()
{
//    wacDebugLog("initWeaveQcFormFormDialog.");
    $("#weaveQcFormFormDialog").dialog({
            bgiframe: true,
            modal: true,
            width: 1050,
            height: 580,
            autoOpen: false,
            buttons: {},
            zIndex: 100
        });
}

function initWeaveQcFormForm()
{
    $("#weaveQcFormForm").validationEngine();

    $.datepicker.setDefaults($.datepicker.regional['zh-CN']);
    $("#weaveQcForm_qc_date").datepicker();

    $('.wacFormContent .left, .wacFormContent input, .wacFormContent textarea, .wacFormContent select').focus(function(){
        $(this).parents('.wacFormContent').addClass("wacFormOver");
    }).blur(function(){
        $(this).parents('.wacFormContent').removeClass("wacFormOver");
    });

    $('.wacFormContentA .left, .wacFormContentA input, .wacFormContentA textarea, .wacFormContentA select').focus(function(){
        $(this).parents('.wacFormRow').addClass("wacFormOver");
    }).blur(function(){
        $(this).parents('.wacFormRow').removeClass("wacFormOver");
    });


}

function initWeaveQcFormFormData()
{
    wacShowBlockUILoading("#weaveQcFormFormDialog");
    $('#weaveQcForm_production_order_id, #weaveQcForm_weave_order_id, #weaveQcForm_goods_id, #weaveQcForm_check_length_unit_code').empty();

    var params = {
        "data_format" :'json'
    };

    $.ajax({
        url: BASE_URL + "weaveQcForm/getFormData",
        global: true,
        type: "GET",
        data: params,
        dataType: "json",
        success: function(jsonData){
            initWeaveQcFormFormDataCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("getFormData Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function initWeaveQcFormFormDataCallBack(jsonData)
{
   if(jsonData.info.status == wacOperationStatus.Error)
   {
       alert(jsonData.info.error_info);
   }
   else
    {
        var selectedIndex = 0;

        for(i=0;i<jsonData['items']['unit'].length;i++)
        {
            $('<option value="' + jsonData['items']['unit'][i].key +'">' + jsonData['items']['unit'][i].value +'</option>').appendTo("#weaveQcForm_check_length_unit_code");
        }
   }

   setupWeaveQcFormFormDefaultValues(jsonData['items']['default']);

   wacHideBlockUI("#weaveQcFormFormDialog");

//   wacDebugLog($.dump(jsonData));
}

function setupWeaveQcFormFormDefaultValues(defaultValueObj)
{
    if(weaveQcFormInputMode == wacFormInputMode.add)   // use default values
    {
        $("#weaveQcForm_id").attr("value", 0);
        $('#weaveQcForm_production_order_id').flexbox(BASE_URL + 'productionOrder/GetIdCodeHashInFormat/status/audited?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "production_order_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });

        $('#weaveQcForm_weave_order_id').flexbox(BASE_URL + 'weaveOrder/GetIdCodeHashInFormat?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "weave_order_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });

        $('#weaveQcForm_goods_id').flexbox(BASE_URL + 'goods/GetWeaveHashInFormat?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "goods_id",
            inputName: "goods_name",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });

        $("#weaveQcForm_check_length_unit_code option:[value='"+ defaultValueObj.check_length_unit_code +"']").attr('selected', 'selected');
    }
    else  // use edit obj values
    {
        $('#weaveQcForm_production_order_id').flexbox(BASE_URL + 'productionOrder/GetIdCodeHashInFormat/status/audited?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            initialValue: weaveQcFormObj.production_order_id,
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "production_order_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });
        $('#weaveQcForm_production_order_id_input').val(weaveQcFormObj.production_order_code);

        $('#weaveQcForm_weave_order_id').flexbox(BASE_URL + 'weaveOrder/GetIdCodeHashInFormat?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            initialValue: weaveQcFormObj.weave_order_id,
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "weave_order_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });
        $('#weaveQcForm_weave_order_id_input').val(weaveQcFormObj.weave_order_code);

        $('#weaveQcForm_goods_id').flexbox(BASE_URL + 'goods/GetWeaveHashInFormat?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            initialValue: weaveQcFormObj.goods_id,
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "goods_id",
            inputName: "goods_name",
            onSelect: function() {
                wacDebugLog('You selected "' + this.value + '", ' +
                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });
        $('#weaveQcForm_goods_id_input').val(weaveQcFormObj.goods_name);

        $("#weaveQcForm_color_check_memo").attr("value", weaveQcFormObj.color_check_memo);
        $("#weaveQcForm_style_check_memo").attr("value", weaveQcFormObj.style_check_memo);
        $("#weaveQcForm_axis_aberration_check_memo").attr("value", weaveQcFormObj.axis_aberration_check_memo);

        $("#weaveQcForm_id").attr("value", weaveQcFormObj.id);
        $("#weaveQcForm_qc_date").attr("value", weaveQcFormObj.qc_date);
        $("#weaveQcForm_code").attr("value", weaveQcFormObj.code);
        $("#weaveQcForm_check_length").attr("value", weaveQcFormObj.check_length);
        $("#weaveQcForm_memo").attr("value", weaveQcFormObj.memo);

        $("#weaveQcForm_color_check").attr("checked", (weaveQcFormObj.color_check==1));
        $("#weaveQcForm_style_check").attr("checked", (weaveQcFormObj.style_check==1));
        $("#weaveQcForm_axis_aberration_check").attr("checked", (weaveQcFormObj.axis_aberration_check==1));
        $("#weaveQcForm_is_thick_warp_yarn").attr("checked", (weaveQcFormObj.is_thick_warp_yarn==1));
        $("#weaveQcForm_is_thick_filling_yarn").attr("checked", (weaveQcFormObj.is_thick_filling_yarn==1));
        $("#weaveQcForm_is_white_spot").attr("checked", (weaveQcFormObj.is_white_spot==1));
        $("#weaveQcForm_is_black_spot").attr("checked", (weaveQcFormObj.is_black_spot==1));
        $("#weaveQcForm_is_exception").attr("checked", (weaveQcFormObj.is_exception==1));
        $("#weaveQcForm_check_point1").attr("checked", (weaveQcFormObj.check_point1==1));
        $("#weaveQcForm_check_point2").attr("checked", (weaveQcFormObj.check_point2==1));
        $("#weaveQcForm_check_point3").attr("checked", (weaveQcFormObj.check_point3==1));
        $("#weaveQcForm_check_point4").attr("checked", (weaveQcFormObj.check_point4==1));
        $("#weaveQcForm_check_point5").attr("checked", (weaveQcFormObj.check_point5==1));
        $("#weaveQcForm_check_point6").attr("checked", (weaveQcFormObj.check_point6==1));
        $("#weaveQcForm_check_point7").attr("checked", (weaveQcFormObj.check_point7==1));

        $("#weaveQcForm_check_length_unit_code option:[value='"+ weaveQcFormObj.check_length_unit_code +"']").attr('selected', 'selected');
    }

//    wacDebugLog($.dump(weaveQcFormObj));
//    wacDebugLog($.dump(defaultValueObj));
//    wacDebugLog("weaveQcFormInputMode: " + weaveQcFormInputMode);

}
/***** init section, end *****/


/**************  interaction section, begin  ***************/
// audit class
function WeaveQcFormAuditAction(){
    this.run = function(orderId){
        weaveQcFormAudit(orderId);
    }
}

function weaveQcFormAudit(orderId)
{
    wacShowBlockUILoading();
    var params = {
        "data_format" : 'json',
        "weave_qc_form_id" : orderId
    };
//    weaveQcFormObj = $("#weaveQcFormList").getRowData(orderId);
//    console.log($.dump(weaveQcFormObj));

    $.ajax({
        url: BASE_URL + "weaveQcForm/audit",
        global: true,
        type: "GET",
        data: params,
        dataType: "json",
        success: function(jsonData){
            weaveQcFormAuditCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("getFormData Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function weaveQcFormAuditCallBack(jsonData)
{
   if(jsonData.info.status == wacOperationStatus.Error)
   {
       wacShowTips(jsonData.info.error_info);
   }
   else
   {
       wacShowTips(jsonData.info.tips);
       $("#weaveQcFormList").trigger("reloadGrid");
   }
   wacHideBlockUI();
//   wacDebugLog($.dump(jsonData));
}

function weaveQcFormOpenModuleForm(moduleFormName, moduleName, inputMode, rowid)
{
    weaveQcFormInputMode = inputMode;

    if(rowid === undefined){
        weaveQcFormObj = {};
    }
    else
    {
        weaveQcFormObj = $("#" + moduleName +"List").getRowData(rowid);
    }

    $('#'+moduleFormName).dialog('open');
}

function validateWeaveQcFormForm()
{
    var validateFlag = true;

    if (!$("#weaveQcFormForm").validationEngine({returnIsValid:true}))
    {
        validateFlag = false;
        return validateFlag;
    }
    

    return validateFlag;
}

function submitWeaveQcFormForm()
{
    if(!validateWeaveQcFormForm()){
        return;
    }

    wacShowBlockUILoading("#weaveQcFormFormDialog", "处理中...");

    var extraParams = "data_format=json";
    var submitUrl;

    if(weaveQcFormInputMode == wacFormInputMode.add){
        submitUrl = BASE_URL + "weaveQcForm/add";
    }
    else{
        submitUrl = BASE_URL + "weaveQcForm/edit";
    }


    $.ajax({
        url: submitUrl,
//        url: BASE_URL + "test/ajaxTest" ,
        global: true,
        type: "GET",
        data: $("#weaveQcFormForm").serialize() + "&" + extraParams,
        dataType: "json",
        success: function(jsonData){
            submitWeaveQcFormFormCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("getFormData Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function submitWeaveQcFormFormCallBack(jsonData)
{
   if(jsonData.info.status == wacOperationStatus.Error)
   {
       wacShowTips(jsonData.info.error_info);
   }
   else
   {
       wacShowTips(jsonData.info.tips);
       $("#weaveQcFormList").trigger("reloadGrid");
   }

   wacHideBlockUI("#weaveQcFormFormDialog");

//   wacDebugLog($.dump(jsonData));
}

/**************  interaction section, end  ***************/